package com.zhongyu.item.consumer.service.Impl;

import com.zhongyu.comm.pojo.Cinema;
import com.zhongyu.comm.pojo.Image;
import com.zhongyu.comm.pojo.Item;
import com.zhongyu.comm.pojo.ItemType;
import com.zhongyu.comm.util.Constants;
import com.zhongyu.item.consumer.client.CinemaClient;
import com.zhongyu.item.consumer.client.ImageClient;
import com.zhongyu.item.consumer.client.ItemClient;
import com.zhongyu.item.consumer.client.ItemTypeClient;
import com.zhongyu.item.consumer.service.ItemService;
import com.zhongyu.item.consumer.vo.ItemDetailVo;
import com.zhongyu.item.consumer.vo.ItemVo;
import javafx.scene.layout.Region;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service("itemService")
@Slf4j
public class ItemServiceImpl implements ItemService {

    @Resource
    private ItemClient itemClient;

    @Resource
    private ImageClient imageClient;
    @Resource
    private CinemaClient cinemaClient;
    @Resource
    private ItemTypeClient itemTypeClient;

    @Resource(name = "myRedisTemplate")
    private RedisTemplate redisTemplate;


    /* @Scheduled(fixedDelay = 1000*30)
    // @Scheduled(cron = "0 0 3 * * ?")
     public void updateRedisItemList(){
         redisTemplate.setKeySerializer(new StringRedisSerializer());
         log.debug("定时更新redis中的数据");
         boolean flag=redisTemplate.hasKey("items:list");
         if (flag){
             redisTemplate.delete("items:list");
         }
        *//* try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*//*
       //ValueOperations<String,Object> valueOperations= redisTemplate.opsForValue();
    ListOperations<String,Object> listOperations= redisTemplate.opsForList();
        List<ItemVo> list=getItemVos();
        listOperations.leftPushAll("items:list",list);
      //valueOperations.set("items:list",list);
    }*/
    @Scheduled(fixedDelay = 10000 * 30000)
    //@Scheduled(cron = "0 0 3 * * ?")
    public void updateRedisItemList() {
        //  redisTemplate.setKeySerializer(new StringRedisSerializer());
        log.debug("定时更新redis中的数据");
        List<ItemVo> itemVos = this.getItemVos();
        HashOperations<String, String, ItemVo> hashOperations = redisTemplate.opsForHash();
        for (ItemVo itemVo : itemVos) {
            hashOperations.putIfAbsent(Constants.Index.FLOOR_ITEM, itemVo.getId() + "", itemVo);
        }
    }

    /***
     * 从redis中查询ItemVo,为楼层FloorItem
     * @return
     */
    //@Cacheable(cacheNames = "items",key="'list'")
    @Override
    public List<ItemVo> searchItems() {
        List<ItemVo> itemVos = null;
      /*  redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());*/
        log.debug("远程查询，并把结果放入redis缓存");
        HashOperations<String, String, ItemVo> hashOperations = redisTemplate.opsForHash();
        itemVos = hashOperations.values(Constants.Index.FLOOR_ITEM);
        if (itemVos == null || itemVos.size() == 0) {
            itemVos = this.getItemVos();
        } else {
            itemVos = this.getItemVos();
            for (ItemVo itemVo : itemVos) {
                hashOperations.putIfAbsent(Constants.Index.FLOOR_ITEM, itemVo.getId() + "", itemVo);
            }
        }
        return itemVos;
    }


    /***
     * 从redis中查询ItemVo,为楼层FloorItem
     * @return*/
    //@Cacheable(cacheNames = "items",key="'list'")
  /* @Override
    public List<ItemVo> searchItems() {
       redisTemplate.setKeySerializer(new StringRedisSerializer());
        log.debug("远程查询，并把结果放入redis缓存");
       boolean flag=redisTemplate.hasKey("items:list");
       ValueOperations<String,Object> valueOperations= redisTemplate.opsForValue();
       List<ItemVo> itemVoList=null;
       if (flag==true){
        itemVoList= (List<ItemVo>) valueOperations.get("items:list");
       }else {
          itemVoList= getItemVos();
       }
       return  itemVoList;
    }
*/

    /**
     * 根据id查询商品详情
     *
     * @param itemId
     * @return
     */
    @Override
    public ItemDetailVo searchItemDetail(Integer itemId) {
        HashOperations<String, String, ItemVo> hashOperations = redisTemplate.opsForHash();
        ItemVo itemVo = null;
        String id = Integer.toString(itemId);
        if (hashOperations.hasKey(Constants.Index.FLOOR_ITEM, id)) {
            itemVo = hashOperations.get(Constants.Index.FLOOR_ITEM, id);
        } else if (hashOperations.hasKey(Constants.Index.RECOMMEND_ITEM, id)) {
            itemVo = hashOperations.get(Constants.Index.RECOMMEND_ITEM, id);
        } else if (hashOperations.hasKey(Constants.Index.BANNER_ITEM, id)) {
            itemVo = hashOperations.get(Constants.Index.BANNER_ITEM, id);
        }
        ItemDetailVo itemDetailVo = new ItemDetailVo();
        BeanUtils.copyProperties(itemVo, itemDetailVo);
        return itemDetailVo;
    }

    private List<ItemVo> getItemVos() {
        List<ItemVo> itemVos = new ArrayList<ItemVo>();
        List<ItemType> itemTypes = itemTypeClient.findByKey();
        itemTypes.stream().forEach(itemType -> {
            List<Item> list = itemClient.findTopN(itemType.getId(), 5);
            for (Item item : list) {
                    ItemVo itemVo = new ItemVo();
                    BeanUtils.copyProperties(item, itemVo);
                    itemVo.setStartDate(item.getStartTime());
                    itemVo.setEndDate(item.getEndTime());
                    Image image = imageClient.findOne(item.getId(), Constants.Image.ImageType.poster, Constants.Image.ImageCategory.item);
                    itemVo.setImgUrl(image.getImgUrl());
                    Cinema cinema = cinemaClient.findById(item.getCinemaId());
                    itemVo.setAddress(cinema.getAddress());
                    itemVo.setAreaId(cinema.getAreaId());
                    itemVo.setAreaName(cinema.getAreaName());
                    itemVos.add(itemVo);
            }
        });
        return itemVos;
    }

  /*  @Scheduled(fixedDelay =1000*60 )
    @CacheEvict(value = "item",allEntries = true,beforeInvocation = true)
    public void removeCache(){
        *//**
     * allEntries=true 清除全部元素
     * beforeTnvocation=true 方法执行之前清楚缓存
     * 代理方式调用进行缓存
     *//*
        log.info("执行清除缓存方法");
        IndexServiceImpl indexService=applicationContext.getBean(IndexServiceImpl.class);
        IndexServiceImpl.searchItems();
    }*/
}
